<template>
  <GlobalContainer className="!bg-[#F3F3F3]" :backgroundImage="`${OSS_URL}/images/jiaofei/jiaofei_bg.png`">
    <GlobalHeader title="物业缴费" showBack :fixed="true" :backgroundImage="`${OSS_URL}/images/jiaofei/jiaofei_bg.png`" />
    <div class="mb-128 mt-24 px-24 pb-safe">
      <div class="payment-records">
        <div class="header flex items-center">
          <image class="mr-16 size-56" src="../../static/images/jiaofei/head_icon.png" />
          <span>{{ accountStore.roomInfo }}</span>
          <div class="log-btn shrink-0" @tap="toJiaofeiLog">缴费记录</div>
        </div>

        <div class="payment-box" v-for="(yearItem, key) of paymentMap" :key="key">
          <template v-if="key !== 'active'">
            <div class="title flex items-center leading-48" @tap.stop="selectedNode(yearItem, !yearItem.active)">
              <div class="select" :class="yearItem.active && 'select-active'" />
              <span v-if="new Date().getFullYear() === Number(key)">今年（{{ key }}年）缴费</span>
              <span v-else>{{ key }}年缴费</span>
            </div>
            <div class="mt-20 flex items-center leading-34">
              <span class="font-weight-400 text-30 text-[#909399]">缴费</span>
              <span class="ml-12 text-34 font-bold text-[#1E90FF]">{{ originList.length }}项</span>
            </div>
            <!--分割 -->
            <div class="my-32 h-1 w-full bg-[#E6E8EB]" />
            <div class="payment-list">
              <template v-for="(typeItem, typeKey) of yearItem" :key="typeKey">
                <template v-if="typeKey !== 'active'">
                  <div class="payment-item" v-for="(numItem, key) of typeItem" :key="key">
                    <template v-if="key !== 'active'">
                      <div class="payment-item-title items-cenfter flex" @tap.stop="selectedNode(typeItem, !typeItem.active)">
                        <div class="select" :class="numItem.active && 'select-active'" />
                        <image class="mr-20 size-40" :src="iconType[typeKey]" />
                        <span>{{ numItem.name }}</span>
                      </div>
                      <div class="payment-item-list">
                        <div
                          class="payment-item-list-item flex items-center"
                          v-for="item of numItem.list"
                          :key="item.id"
                          @tap.stop="selectItem(item)"
                        >
                          <div class="select" :class="item.active && 'select-active'" />
                          <span>{{ item.name }}</span>
                          <span class="price ml-auto">￥{{ item.amount }}</span>
                        </div>
                      </div>
                      <div v-if="index !== typeItem.length - 1" class="my-32 h-1 w-full bg-[#E6E8EB]" />
                    </template>
                  </div>
                </template>
              </template>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="payment-btn flex w-full items-center pb-safe">
      <div class="left flex items-center" @tap="selectedNode(paymentMap, !paymentMap.active)">
        <div class="select" :class="paymentMap.active && 'select-active'" />
        <div class="text-26 text-[#303133]">全选</div>
      </div>
      <div class="right ml-auto flex items-center text-[#909399]">
        <div class="flex flex-col items-end text-24">
          <div class="flex items-center">
            <span class="">共计</span>
            <span class="text-34 font-bold text-[#303133]">￥{{ totalAmount }}</span>
          </div>
          <div class="flex items-center">
            <span class="">已选{{ selectedList.length }}项目</span>
          </div>
        </div>
        <div class="disabled ml-20" :class="selectedList.length > 0 && 'default'" @tap="toPay">去缴费</div>
      </div>
    </div>
    <div class="h-20" />
  </GlobalContainer>
</template>

<script setup>
import { computed } from 'vue'
import { useAccountStore } from '@/store/modules/account'
import { getPaymentBill, createPropertyOrder, propertyPayment } from '@/common/api/order'
const accountStore = useAccountStore()
const OSS_URL = import.meta.env.VITE_OSS_URL
const iconType = {
  room: `${OSS_URL}/images/jiaofei/home_icon.png`,
  car: `${OSS_URL}/images/jiaofei/car_icon.png`
}
const originList = ref([])
const paymentMap = ref({})
const selectedList = ref([])
const totalAmount = computed(() => {
  return selectedList.value.reduce((total, item) => total + item.amount, 0).toFixed(2)
})
const selectItem = item => {
  console.log('[ item ] >', item)
  item.active = !item.active
  selectedList.value = []
  updateParentActive(paymentMap.value)
}
function selectedNode(item, active) {
  selectedList.value = []
  updateChildrenActive(item, active)
}

function updateParentActive(obj) {
  for (const key in obj) {
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      // 如果当前对象有 active 属性和 list 属性
      if (obj[key]['list']) {
        // 根据 list 中子节点的 active 状态更新当前对象的 active 状态
        obj[key]['active'] = obj[key]['list'].every(item => {
          return item['active']
        })
        obj[key]['list'].forEach(item => {
          if (item['active']) {
            selectedList.value.push(item)
          }
        })
      } else {
        updateParentActive(obj[key])
      }
    }
  }
  console.log('[ selectedList ] >', selectedList.value)
}

// 递归函数，用于更新子节点的 active 状态
function updateChildrenActive(obj, active) {
  obj.active = active
  for (const key in obj) {
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      // 如果当前属性是对象，递归调用函数
      updateChildrenActive(obj[key], active)

      // 如果当前对象有 active 属性
      if (obj[key]['active']) {
        // 将当前对象的 active 属性设置为指定的值
        obj[key]['active'] = active
      }

      // 如果当前对象有 list 属性
      if (obj[key]['list']) {
        // 将 list 中所有子节点的 active 属性设置为指定的值
        obj[key]['list'].forEach(item => {
          item['active'] = active
          if (active) {
            selectedList.value.push(item)
          }
        })
      }
    }
  }
}
const getPaymentBillList = () => {
  uni.showLoading({
    title: '加载中'
  })
  getPaymentBill({
    pageNo: 1,
    pageSize: 9999,
    payStatus: 0
  })
    .then(res => {
      console.log(res.records)
      const map = {
        active: false
      }
      // 根据年份分组
      // 结构
      // {
      //   '2024': {
      //     room: {
      //       active: false,
      //       roomId: {
      //         active: false,
      //         list: [
      //           {
      //             active: false,
      //             name: '2024-01',
      //             amount: 123.4
      //           }
      //         ]
      //       }
      //     },
      //     car: {
      //       parkingNumber: {
      //         active: false,
      //         list: [
      //           {
      //             active: false,
      //             name: '2024-01',
      //             amount: 123.4
      //           }
      //         ]
      //       }}
      //   }
      // }
      originList.value = res.records
      res.records.forEach(item => {
        item.active = false
        if (!map[item.year]) {
          map[item.year] = {
            active: false
          }
        }
        if (item.type === 0) {
          if (!map[item.year]['room']) {
            map[item.year]['room'] = {
              active: false
            }
          }
          if (!map[item.year]['room'][item.roomId]) {
            map[item.year]['room'][item.roomId] = {
              name: accountStore.roomInfo,
              active: false,
              list: []
            }
          }
          map[item.year]['room'][item.roomId].list.push(item)
        } else {
          if (!map[item.year]['car']) {
            map[item.year]['car'] = {
              active: false
            }
          }
          if (!map[item.year]['car'][item.parkingNumber]) {
            map[item.year]['car'][item.parkingNumber] = {
              name: `${item.parkingNumber}号车位`,
              active: false,
              list: []
            }
          }
          map[item.year]['car'][item.parkingNumber].list.push(item)
        }
      })
      console.log('[ map ] >', map)
      paymentMap.value = map
    })
    .finally(() => {
      uni.hideLoading()
    })
}
getPaymentBillList()
const toJiaofeiLog = () => {
  uni.navigateTo({
    url: '/subPages/jiaofeiLog/index'
  })
}

const toPay = () => {
  if (selectedList.value.length === 0) {
    uni.showToast({
      title: '请选择缴费项目'
    })
    return
  }
  createPropertyOrder({
    propertyBillIds: selectedList.value.map(item => item.id)
  }).then(res => {
    if (res.id) {
      // 拉起支付
      propertyPayment({
        orderNo: res.orderNo
      }).then(res => {
        if (res.prepayId) {
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: String(res.timeStamp),
            nonceStr: res.nonceStr,
            package: 'prepay_id=' + res.prepayId,
            signType: 'SHA256withRSA',
            paySign: res.paySign,
            orderInfo: {
              appId: '',
              timeStamp: String(res.timeStamp),
              nonceStr: res.nonceStr,
              package: ''
            },
            success: function (res) {},
            complete: function () {
              uni.redirectTo({
                url: '/subPages/jiaofeiLog/index'
              })
            }
          })
        }
      })
    }
  })
}

// 根据传入的结构，设置active
const setActive = data => {
  data.forEach(item => {
    item.active = true
  })
}
</script>
<style lang="scss" scoped>
.select {
  flex-shrink: 0;
  margin-right: 20rpx;
  width: 32rpx;
  height: 32rpx;
  background: #ffffff;
  border-radius: 50%;
  border: 1px solid #d4d7de;
}
.select-active {
  background: #ffffff;
  border-radius: 1000rpx 1000rpx 1000rpx 1000rpx;
  border: 8rpx solid #1e90ff;
}
.payment-records {
}
.header {
  font-size: 34rpx;
  color: #303133;
  line-height: 40rpx;
  margin-bottom: 29rpx;
  .log-btn {
    margin-left: auto;
    padding: 0 28rpx;
    line-height: 60rpx;
    background: #fafafa;
    border-radius: 40rpx;
    border: 2rpx solid #cdd0d6;
    font-size: 26rpx;
    color: #606266;
    text-align: center;
  }
}
.payment-box {
  background: #fcfeff;
  border-radius: 20rpx;
  border: 1rpx solid #ffffff;
  padding: 40rpx 34rpx 50rpx 42rpx;
}

.payment-item-title {
  font-size: 32rpx;
  color: #303133;
  line-height: 1;
}
.payment-item-list-item {
  margin-top: 36rpx;
  font-size: 30rpx;
  color: #2e3a59;
  line-height: 46rpx;
  .price {
    color: #303133;
  }
}

.payment-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding-left: 30rpx;
  box-shadow: 0rpx -2rpx 12rpx 0rpx rgba(89, 118, 178, 0.15);
}
.payment-btn .disabled {
  background: #c7c9cc;
  height: 100%;
  width: 200rpx;
  text-align: center;
  line-height: 108rpx;
  color: #ffffff;
}
.payment-btn .default {
  background: #1e90ff;
  color: #ffffff;
}
</style>
